<script setup>
import {onBeforeMount, ref} from "vue";
import ChatUpload from "@/components/chat-upload.vue";
import {userInfo} from "@/stores/userStore.js";
import {deleteById, searchUnStructuredDatas, submitUnstructured, updateEnable} from "@/api/http/chat-knowledge.js";
import {ElMessage} from "element-plus";
import moment from "moment";
import ChatFilePreview from "@/components/chat-file-preview.vue";
import {globalOptions} from "@/api/http/globalconfig.js";


const tableData = ref([]);

const dialogShow = ref(false);
const drawerShow = ref(false);
const tableLoading = ref(false);
const openDialog = () => {
  dialogShow.value = !dialogShow.value;
}

const fileTabFormVal = ref({});
const chatUploadRef = ref();
const limitFileType = ref();


const resetFileTabFormVal = () => {
  fileTabFormVal.value = {};
  chatUploadRef.value.initFunc();
}

const searchTableDatas = async () => {
  tableLoading.value = true;
  await searchUnStructuredDatas({
    "userId": userInfo().userId,
    'knowledgeType': 'unstructured'
  })
      .then(res => {
        tableData.value = res.data.data
        tableLoading.value = false;
      })
      .catch(res => {
        tableLoading.value = false;
      })
}

const submitFileTab = () => {

  const formValParam = {};
  let originFileList = fileTabFormVal.value?.fileList;
  originFileList = (originFileList === undefined || originFileList.length === 0) ? [] : originFileList;
  const fileIds = originFileList
      .filter(a => {
        return a.response?.code === 200;
      })
      .map(a => {
        return a.response.data.fileId;
      });
  formValParam['fileList'] = fileIds;

  if (fileTabFormVal.value?.documentUrl !== undefined) {
    formValParam['documentUrl'] = Object.values(fileTabFormVal.value?.documentUrl)
  }

  if (fileTabFormVal.value?.fileUrl !== undefined) {
    formValParam['fileUrl'] = Object.values(fileTabFormVal.value?.fileUrl)
  }
  formValParam['userId'] = userInfo().userId;

  submitUnstructured(formValParam)
      .then(res => {
        if (res.data.code === 200) {
          ElMessage({
            type: "success",
            message: `提交成功`
          })
          dialogShow.value = false;
          searchTableDatas();
        } else {
          ElMessage({
            type: "error",
            message: `提交失败:${res.data.message}`
          })
        }

      }).catch(res => {
  })
}
const updateEnableStatusFunc = (param) => {
  updateEnable(param)
      .then((res) => {
        if (res.data.data) {
          ElMessage({
            type: "success",
            message: "启用状态更新成功!"
          })
        }
      })
}

const deleteByIdFunc = (id) => {
  deleteById(id)
      .then(res => {
        ElMessage({
          type: "success",
          message: "删除成功"
        });
        searchTableDatas();
      })
}

onBeforeMount(async () => {
  await searchTableDatas();
  await globalOptions().then(res => {
    limitFileType.value = res.data.data.supportFileTypes;
  })
})
</script>

<template>
  <div class="unstructured-data-wrapper">
    <div style="flex-grow: 1">
      <div>
        <el-button
            @click="openDialog"
            type="primary"
            plain
        >导入
        </el-button>
        <el-button
            @click="searchTableDatas"
        >搜索
        </el-button>
      </div>
      <el-table
          row-key="id"
          :data="tableData"
          max-height="80vh"
          v-loading="tableLoading"
      >
        <template #empty
        >
          点击导入按钮进行上传文件吧
        </template>
        <el-table-column align="center" type="index" :index="index => index+1"/>
        <el-table-column label="文件" prop="fileName">
          <template #default="{row}">
            <el-popover
                width="600px"
                placement="top-start"
            >
              <template #reference>
                <el-tag type="info">{{ row.fileName }}</el-tag>
              </template>
              <template #default>
                <el-descriptions
                    title="文件信息"
                    size="small"
                    :column="1"
                >
                  <el-descriptions-item label="ID">{{ row.fileId }}</el-descriptions-item>
                  <el-descriptions-item label="文件名">{{ row.fileName }}</el-descriptions-item>
                  <el-descriptions-item label="路径">{{ row.path }}</el-descriptions-item>
                  <el-descriptions-item label="链接">
                    <el-text>{{ row.url }}</el-text>
                  </el-descriptions-item>
                </el-descriptions>
              </template>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column label="文件状态">
          <template #default="{row}">
            <el-popover
                width="600px"
                placement="top-start"
            >
              <el-timeline>
                <el-timeline-item
                    v-for="(activity, index) in row.operateList??[]"
                    :key="index"
                    :timestamp="activity.operateTime"
                >
                  {{
                    `${activity.statusText}${(activity.msg === null || activity.msg === '') ? '' : "(" + activity.msg + ")"}`
                  }}
                </el-timeline-item>
              </el-timeline>
              <template #reference>
                <el-tag type="info">{{ row.statusText }}</el-tag>
              </template>

            </el-popover>

          </template>
        </el-table-column>
        <el-table-column align="center" label="更新时间" prop="modifyTime">
          <template #default="{row}">
            <div style="display: flex;align-items: center;justify-content: center">
              <el-icon style="margin-right: 8px">
                <timer/>
              </el-icon>
              <el-text>{{ moment(row.modifyTime).format('YYYY-MM-DD HH:mm') }}</el-text>
            </div>

          </template>
        </el-table-column>
        <el-table-column align="center" label="操作人" prop="createBy">
        </el-table-column>
        <el-table-column align="center" label="启用">
          <template #default="{row}">
            <el-switch
                @change="updateEnableStatusFunc({
                  'recordId':row.id,
                  'enable':row.enable
                })"
                v-model="row.enable"
                :active-value="1"
                :inactive-value="0"
            />
          </template>
        </el-table-column>
        <el-table-column
            width="240px"
            align="center" label="操作">
          <template #default="{row,scope}"
          >
            <el-button type="info"
                       plain
                       @click="drawerShow=true"
                       size="small"
                       :disabled="!row?.permission?.enablePreview"
            >预览
            </el-button>
            <el-button type="success"
                       size="small"
                       :disabled="!row?.permission?.enableAiBtn"
                       plain>AI
            </el-button>
            <el-button type="warning" size="small"
                       :disabled="!row?.permission?.enableLoad"
                       plain>重试
            </el-button>

            <el-popconfirm
                title="确认要删除吗?"
                placement="bottom-start"
                confirm-button-text="确认"
                cancel-button-text="取消"
                @confirm="deleteByIdFunc(row.id)"
            >
              <template #reference>
                <el-button type="danger" size="small"
                           :disabled="!row?.permission?.enableDeleted"
                           plain>删除
                </el-button>
              </template>
            </el-popconfirm>

          </template>

        </el-table-column>
      </el-table>
    </div>
  </div>


  <el-drawer
      v-model="drawerShow"
      size="60%"
  >
    <chat-file-preview/>
  </el-drawer>
  <!--  导入对话框-->
  <el-dialog
      v-model="dialogShow"
      @close="resetFileTabFormVal"
  >
    <el-tabs>
      <el-tab-pane label="文件">
        <el-form
            ref="fileFromRef"
            :model="fileTabFormVal"
            label-width="auto"
            label-suffix=":"
        >
          <el-form-item label="文件" :prop="fileTabFormVal.fileList">
            <chat-upload
                :limit-type="limitFileType"
                limit-size="2"
                v-model:fileList="fileTabFormVal.fileList"
                ref="chatUploadRef"
            />
          </el-form-item>
          <el-form-item label="文件链接" :prop="fileTabFormVal.fileUrl">
            <el-input-tag
                disabled
                v-model="fileTabFormVal.fileUrl"
                clearable
                placeholder="暂不支持"
            />
          </el-form-item>
          <el-form-item label="文档地址" :prop="fileTabFormVal.documentUrl">
            <el-input-tag
                disabled
                v-model="fileTabFormVal.documentUrl"
                clearable
                placeholder="暂不支持"
            />
          </el-form-item>
          <el-form-item>
            <el-button @click="submitFileTab">提交</el-button>
            <el-button @click="resetFileTabFormVal">重置</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>
    </el-tabs>
  </el-dialog>
</template>

<style scoped lang="scss">
.unstructured-data-wrapper {
  display: flex;

  & > div {
    margin: 0 16px 0 16px
  }
}
</style>